<template>
  <el-drawer
    v-model="visible"
    title=""
    size="700px"
    direction="rtl"
    :before-close="handleClose"
    class="create-doc-drawer"
  >
    <template #header>
      <div class="drawer-header">
        <div class="drawer-title">
          <div class="title-bar"></div>
          <span>{{ props.isEditMode ? '修改文档' : '新建文档' }}</span>
        </div>
      </div>
    </template>

    <div class="drawer-content">
      <!-- 表单内容 -->
      <div class="form-content">
        <!-- 文档分类 -->
        <div class="form-item">
          <div class="form-label">
            <el-icon><Folder /></el-icon>
            文档分类
            <span class="required-mark">*</span>
          </div>
          <el-tree-select
            v-model="uploadForm.categoryId"
            :data="treeCategories"
            placeholder="请选择文档分类"
            style="width: 100%"
            class="category-tree-select"
             :props="{ label: 'type_name', value: 'id', children: 'children' }"
            check-strictly
            :render-after-expand="false"
            :expand-on-click-node="false"
            filterable
          />
        </div>

        <!-- 文档类型 -->
        <div class="form-item">
          <div class="form-label">
            <el-icon><Document /></el-icon>
            文档类型
            <span class="required-mark">*</span>
          </div>
          <el-select
            v-model="uploadForm.documentType"
            placeholder="请选择文档类型"
            style="width: 100%"
            class="doc-type-select"
          >
            <el-option v-for="item in documentTypeOptions" :key="item.value" :label="item.value" :value="item.key" />
<!--            <el-option label="技术文档" value="technical" />-->
<!--            <el-option label="管理制度" value="management" />-->
<!--            <el-option label="操作手册" value="manual" />-->
<!--            <el-option label="规范标准" value="standard" />-->
<!--            <el-option label="培训资料" value="training" />-->
<!--            <el-option label="其他" value="other" />-->
          </el-select>
        </div>

        <!-- 文档概述 -->
        <div class="form-item">
          <div class="form-label">
            <el-icon><Edit /></el-icon>
            文档概述
          </div>
          <el-input
            v-model="uploadForm.documentOverview"
            type="textarea"
            :rows="4"
            placeholder="请简要描述文档的主要内容和用途..."
            style="width: 100%"
            class="doc-overview-textarea"
            maxlength="500"
            show-word-limit
          />
          <div class="form-tip">
            💡 提示：文档概述将帮助其他用户更好地理解和检索此文档
          </div>
        </div>

        <!-- 文档配置区域 -->
        <div class="document-config-section" v-if="currentDocument">
          <div class="config-header">
            <el-icon><Document /></el-icon>
            <span class="config-title">为文档 "{{ currentDocument.name }}" 配置信息</span>
          </div>
          
                     <!-- 关键词配置 -->
           <div class="config-item">
             <div class="config-label">
            <el-icon><Key /></el-icon>
               关键词
          </div>  
             <div class="config-input-container">
               <div class="keywords-input-container">
                 <div class="keywords-display">
                   <el-tag
                     v-for="(keyword, index) in documentKeywords[currentDocument.id]"
                     :key="index"
                     closable
                     @close="removeKeyword(currentDocument.id, index)"
                     class="keyword-item"
                   >
                     {{ keyword }}
                   </el-tag>
                 </div>
                 <el-input
                   v-model="keywordInputValue"
                   placeholder="请输入关键词，按回车键添加"
                   @keyup.enter="addKeyword"
                   @blur="addKeyword"
                   class="keyword-input"
                   ref="keywordInputRef"
                 />
               </div>
          <div class="form-tip">
                 💡 提示：输入关键词后按回车键或失去焦点时添加
               </div>
             </div>
           </div>

                     <!-- 标签配置 -->
           <div class="config-item">
             <div class="config-label">
               <el-icon><Collection /></el-icon>
               标签
             </div>
             <div class="config-input-container">
               <div class="tags-input-container">
                 <div class="tags-display">
                   <el-tag
                     v-for="(tag, index) in documentTags[currentDocument.id]"
                     :key="index"
                     closable
                     @close="removeTag(currentDocument.id, index)"
                     class="tag-item"
                   >
                     {{ tag }}
                   </el-tag>
                 </div>
                 <el-input
                   v-model="tagInputValue"
                   placeholder="请输入标签，按回车键添加"
                   @keyup.enter="addTag"
                   @blur="addTag"
                   class="tag-input"
                   ref="tagInputRef"
                 />
               </div>
               <div class="form-tip">
                 💡 提示：输入标签后按回车键或失去焦点时添加
               </div>
             </div>
          </div>


        </div>

        <!-- 检索范围 -->
<!--        <div class="form-item">-->
<!--          <div class="form-label">-->
<!--            <el-icon><Search /></el-icon>-->
<!--            检索范围-->
<!--            <span class="form-label-note">（限定20个文件内）</span>-->
<!--          </div>-->
<!--          <el-tree-select-->
<!--            v-model="localSearchScope"-->
<!--            :data="enterpriseCategories"-->
<!--            placeholder="请选择企业知识库分类"-->
<!--            style="width: 100%"-->
<!--            class="scope-tree-select"-->
<!--            :props="{ label: 'name', value: 'id', children: 'children' }"-->
<!--            node-key="id"-->
<!--            filterable-->
<!--            multiple-->
<!--            show-checkbox-->
<!--            clearable-->
<!--            @check="onTreeCheck"-->
<!--          />-->



          <!-- 显示已选择的检索范围 AI提取 -->
         <!--  <div v-if="uploadForm.searchScope && uploadForm.searchScope.length > 0" class="selected-scope-display">
            <div class="selected-scope-title">已选择的检索范围：</div>
            <div class="selected-scope-tags">
              <el-tag
                v-for="displayItem in getDisplayScopeItems()"
                :key="displayItem.id"
                :type="displayItem.isParent ? 'primary' : 'info'"
                size="small"
                closable
                @close="removeScopeSelection(displayItem.id)"
              >
                <span v-if="displayItem.isParent">📁 {{ displayItem.name }}</span>
                <span v-else>📄 {{ displayItem.name }}</span>
              </el-tag>
            </div>
          </div> -->
<!--        </div>-->

        <!-- 文档概述 AI提取 -->
<!--        <div class="form-item">-->
<!--          <div class="form-label">-->
<!--            <el-icon><Edit /></el-icon>-->
<!--            文档概述-->
<!--          </div>-->
<!--          <el-input-->
<!--            v-model="uploadForm.documentOverview"-->
<!--            type="textarea"-->
<!--            :rows="4"-->
<!--            placeholder="请简要描述文档的主要内容和用途..."-->
<!--            style="width: 100%"-->
<!--            class="doc-overview-textarea"-->
<!--            maxlength="500"-->
<!--            show-word-limit-->
<!--          />-->
<!--          <div class="form-tip">-->
<!--            💡 提示：文档概述将帮助其他用户更好地理解和检索此文档-->
<!--          </div>-->
<!--        </div>-->

        <!-- 附件上传 -->
        <div class="form-item">
          <div class="form-label-with-close">
            <div class="form-label">附件上传</div>
            <el-icon class="close-icon"><Close /></el-icon>
          </div>

          <div class="upload-area">
            <div class="upload-zone" @click="triggerUpload" @drop="handleDrop" @dragover="handleDragOver">
              <div class="upload-icon">
                <el-icon size="40" color="#409EFF"><Plus /></el-icon>
              </div>
              <div class="upload-text">
                <div class="upload-title">将文件拖拽到此区域，或<span class="upload-link">点击此处</span></div>
                <div class="upload-desc">支持Word、PDF等文件，单文件不超过200M</div>
              </div>
            </div>

            <!-- 已上传文件列表 -->
            <div v-if="uploadedDocFiles.length > 0" class="uploaded-files-list">
              <div 
                v-for="file in uploadedDocFiles" 
                :key="file.id" 
                class="uploaded-file-item"
                :class="{ 'current-file': currentDocument && currentDocument.id === file.id }"
                @click="handleFileClick(file)"
              >
                <div class="file-icon">
                  <Icon :icon="getFileIconClass(file)" style="width: 48px;height: 48px;" />
                  <div class="file-type-badge">{{ getFileExtension(file.name) }}</div>
                </div>
                <div class="file-info">
                  <div class="file-name">{{ file.name }}</div>
                                     <div class="file-details">
                     <span class="file-size">{{ formatFileSize(file.size) }}</span>
                     <span v-if="documentKeywords[file.id] && documentKeywords[file.id].length > 0" class="keywords-badge">
                       {{ documentKeywords[file.id].length }} 个关键词
                     </span>
                     <span v-if="documentTags[file.id] && documentTags[file.id].length > 0" class="tags-badge">
                       {{ documentTags[file.id].length }} 个标签
                     </span>
                   </div>
                </div>
                <div class="file-actions">
                  <div class="action-icon delete-icon" @click.stop="removeUploadedFile(file.id)" title="删除">
                    <el-icon size="16">
                      <Delete />
                    </el-icon>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>


    </div>

    <!-- 抽屉底部操作区 -->
    <div class="drawer-footer">
        <el-button @click="handleClose" class="minimal-btn minimal-btn--secondary">
          取消
        </el-button>
        <el-button @click="handleUploadSubmit" class="gradient-btn">
          上传
        </el-button>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInputRef"
      type="file"
      multiple
      accept=".doc,.docx,.pdf,.txt,.xlsx,.xls"
      @change="handleFileUpload"
      style="display: none"
    />
  </el-drawer>
</template>

<script setup lang="ts">
import { computed, ref, watch, nextTick, onMounted } from 'vue'
import { Folder, Key, Search, Close, Plus, View, Delete, Document, Edit, Collection } from '@element-plus/icons-vue'
import {type Doctype, getKnowledgeDoctype} from "@/api/knowledge/api.ts";
import { Icon } from "@iconify/vue";

interface Props {
  visible: boolean
  currentStep?: number
  uploadForm?: any
  flatCategories?: any[]
  treeCategories?: any[]
  enterpriseCategories?: any[]
  suggestedKeywords?: string[]
  uploadedDocFiles?: any[]
  aiReviewResults?: any[]
  isEditMode?: boolean
  editingDocId?: string | null
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'update:currentStep', value: number): void
  (e: 'update:uploadForm', value: any): void
  (e: 'close'): void
  (e: 'uploadSubmit'): void
  (e: 'previousStep'): void
  (e: 'finalSubmit'): void
  (e: 'fileUpload', event: Event): void
  (e: 'drop', event: DragEvent): void
  (e: 'dragOver', event: DragEvent): void
  (e: 'triggerUpload'): void
  (e: 'previewUploadedFile', file: any): void
  (e: 'removeUploadedFile', id: string): void
  (e: 'showConflictDetail', result: any): void
  (e: 'downloadConflictFile', result: any): void
  (e: 'getFileIconClass', file: any): string
  (e: 'getFileExtension', filename: string): string
  (e: 'formatFileSize', size: number): string
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const fileInputRef = ref<HTMLInputElement>()
const tagInputRef = ref<HTMLInputElement>()
const keywordInputRef = ref<HTMLInputElement>()

// 当前选中的文档
const currentDocument = ref<any>(null)

// 每个文档的关键词映射
const documentKeywords = ref<Record<string, string[]>>({})

// 每个文档的标签映射
const documentTags = ref<Record<string, string[]>>({})



// 标签输入值
const tagInputValue = ref<string>('')

// 关键词输入值
const keywordInputValue = ref<string>('')

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const currentStep = computed({
  get: () => props.currentStep || 1,
  set: (value) => emit('update:currentStep', value)
})

const uploadForm = computed({
  get: () => props.uploadForm || { categoryId: '', documentType: '', keywords: [], searchScope: [], documentOverview: '' },
  set: (value) => emit('update:uploadForm', value)
})

// 直接使用传入的树形分类数据
const treeCategories = computed(() => {
  console.log('treeCategories computed - props.treeCategories:', props.treeCategories)
  return props.treeCategories || []
})
const enterpriseCategories = computed(() => props.enterpriseCategories || [])
const suggestedKeywords = computed(() => props.suggestedKeywords || [])
const uploadedDocFiles = computed(() => props.uploadedDocFiles || [])
const aiReviewResults = computed(() => props.aiReviewResults || [])

// 本地搜索范围变量，用于树形选择器的双向绑定
const localSearchScope = ref<string[]>([])

// 监听uploadForm的变化，同步到本地变量
watch(() => uploadForm.value.searchScope, (newScope) => {
  localSearchScope.value = newScope || []
}, { immediate: true })

const documentTypeOptions = ref<Doctype[]>([])

// 获取文档类型
const getDocumentTypeOptions = async () => {
  getKnowledgeDoctype().then((res) => {
    documentTypeOptions.value = res
  }).catch((error) => {
    console.debug(error)
  });
}
getDocumentTypeOptions()

// 组件挂载时检查是否需要自动选中文件
onMounted(() => {
  console.log('Component mounted, checking for files to auto-select')
  if (props.uploadedDocFiles && props.uploadedDocFiles.length > 0 && !currentDocument.value) {
    const latestFile = props.uploadedDocFiles[props.uploadedDocFiles.length - 1]
    console.log('Auto-selecting file on mount:', latestFile)
    handleFileClick(latestFile)
  }
})


const triggerUpload = () => {
  fileInputRef.value?.click()
  emit('triggerUpload')
}

// 监听文件列表变化，自动选中最新上传的文件
watch(() => props.uploadedDocFiles, async (newFiles, oldFiles) => {
  console.log('Watch triggered - newFiles:', newFiles?.length, 'oldFiles:', oldFiles?.length)
  console.log('Current document:', currentDocument.value)
  
  if (newFiles && newFiles.length > 0) {
    // 如果有文件且没有当前选中的文档，则选中最新上传的文件
    if (!currentDocument.value) {
      const latestFile = newFiles[newFiles.length - 1]
      console.log('Auto-selecting latest file:', latestFile)
      if (latestFile) {
        console.log('Auto-selecting latest file:', latestFile.name)
        // 等待DOM更新完成后再选中文件
        await nextTick()
        handleFileClick(latestFile)
      }
    }
  }
}, { deep: true, immediate: true })

const handleFileUpload = (event: Event) => {
  emit('fileUpload', event)
}

const handleDrop = (event: DragEvent) => {
  emit('drop', event)
}

const handleDragOver = (event: DragEvent) => {
  emit('dragOver', event)
}

const handleUploadSubmit = () => {
  emit('uploadSubmit')
}

const handlePreviousStep = () => {
  emit('previousStep')
}

const handleFinalSubmit = () => {
  emit('finalSubmit')
}

const handleClose = () => {
  // 清空本地数据
  documentKeywords.value = {}
  documentTags.value = {}
  currentDocument.value = null
  tagInputValue.value = ''
  keywordInputValue.value = ''
  
  emit('close')
}

const previewUploadedFile = (file: any) => {
  emit('previewUploadedFile', file)
}

const removeUploadedFile = (id: string) => {
  emit('removeUploadedFile', id)
}

// 文件点击事件
const handleFileClick = (file: any) => {
  console.log('handleFileClick called with file:', file)
  currentDocument.value = file
  // 如果该文档还没有关键词配置，初始化一个空数组
  if (!documentKeywords.value[file.id]) {
    documentKeywords.value[file.id] = []
  }
  // 如果该文档还没有标签配置，初始化一个空数组
  if (!documentTags.value[file.id]) {
    documentTags.value[file.id] = []
  }

  // 清空标签输入值
  tagInputValue.value = ''
  // 清空关键词输入值
  keywordInputValue.value = ''
  console.log('Current document set to:', currentDocument.value)
}

// 添加标签
const addTag = () => {
  if (!currentDocument.value || !tagInputValue.value.trim()) return
  
  const tag = tagInputValue.value.trim()
  const fileId = currentDocument.value.id
  
  // 检查标签是否已存在
  if (!documentTags.value[fileId].includes(tag)) {
    documentTags.value[fileId].push(tag)
    
    // 同步到uploadForm
    const newForm = { ...uploadForm.value }
    newForm.searchScope = documentTags.value[fileId]
    emit('update:uploadForm', newForm)
  }
  
  // 清空输入值
  tagInputValue.value = ''
}

// 移除标签
const removeTag = (fileId: string, index: number) => {
  if (documentTags.value[fileId]) {
    documentTags.value[fileId].splice(index, 1)
    
    // 同步到uploadForm
    const newForm = { ...uploadForm.value }
    newForm.searchScope = documentTags.value[fileId]
    emit('update:uploadForm', newForm)
  }
}

// 添加关键词
const addKeyword = () => {
  if (!currentDocument.value || !keywordInputValue.value.trim()) return
  
  const keyword = keywordInputValue.value.trim()
  const fileId = currentDocument.value.id
  
  // 检查关键词是否已存在
  if (!documentKeywords.value[fileId].includes(keyword)) {
    documentKeywords.value[fileId].push(keyword)
    
    // 同步到uploadForm
    const newForm = { ...uploadForm.value }
    newForm.keywords = documentKeywords.value[fileId]
    emit('update:uploadForm', newForm)
  }
  
  // 清空输入值
  keywordInputValue.value = ''
}

// 移除关键词
const removeKeyword = (fileId: string, index: number) => {
  if (documentKeywords.value[fileId]) {
    documentKeywords.value[fileId].splice(index, 1)
    
    // 同步到uploadForm
    const newForm = { ...uploadForm.value }
    newForm.keywords = documentKeywords.value[fileId]
    emit('update:uploadForm', newForm)
  }
}



const showConflictDetail = (result: any) => {
  emit('showConflictDetail', result)
}

const downloadConflictFile = (result: any) => {
  emit('downloadConflictFile', result)
}

const getFileIconClass = (file: any) => {
  // 修改时请全局搜素 GHDSYU 同步修改
  // icon class 搜索地址https://icon-sets.iconify.design/
  switch (file.type) {
    case 'application/pdf':
      return 'vscode-icons:file-type-pdf2'
    case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
      return 'vscode-icons:file-type-word'
    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
      return 'vscode-icons:file-type-excel'
    default:
      return 'vscode-icons:file-type-taskfile'
  }
}

const getFileExtension = (filename: string) => {
  emit('getFileExtension', filename)
  const ext = filename.split('.').pop()
  return ext?.toUpperCase() || ''
}

const formatFileSize = (size: number) => {
  emit('formatFileSize', size)
  if (size === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(size) / Math.log(k))
  return parseFloat((size / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

// 获取选中的分类名称
const getSelectedCategoryName = () => {
  if (!uploadForm.value.categoryId) return '未选择'

  const findCategoryName = (categories: any[], id: string): string => {
    for (const category of categories) {
      if (category.id === id) return category.type_name
      if (category.children) {
        const found = findCategoryName(category.children, id)
        if (found) return found
      }
    }
    return '未知分类'
  }

  return findCategoryName(treeCategories.value, uploadForm.value.categoryId)
}

// 获取文档类型名称
const getDocumentTypeName = () => {
  const typeMap: Record<string, string> = {
    'technical': '技术文档',
    'management': '管理制度',
    'manual': '操作手册',
    'standard': '规范标准',
    'training': '培训资料',
    'other': '其他'
  }
  
  return typeMap[uploadForm.value.documentType] || '未选择'
}

// 获取选中的检索范围名称（用于AI审核步骤显示）
const getSelectedScopeNames = () => {
  console.log('getSelectedScopeNames 被调用')
  console.log('uploadForm.value.searchScope:', uploadForm.value.searchScope)

  if (!uploadForm.value.searchScope || uploadForm.value.searchScope.length === 0) {
    console.log('searchScope 为空，返回未选择')
    return '未选择'
  }

  const displayItems = getDisplayScopeItems()
  console.log('getSelectedScopeNames - displayItems:', displayItems)
  const names = displayItems.map(item => item.name)
  console.log('getSelectedScopeNames - names:', names)

  const result = names.join('、') || '未选择'
  console.log('getSelectedScopeNames - 最终结果:', result)
  return result
}

// 获取冲突数量
const getConflictCount = () => {
  return aiReviewResults.value.filter(result => result.status === 'error').length
}

// 处理树复选框变化
const onTreeCheck = (data: any, checked: any) => {
  console.log('树复选框变化:', data, checked)
  console.log('checked 对象:', checked)
  console.log('checked.checkedKeys:', checked?.checkedKeys)
  console.log('checked.checkedNodes:', checked?.checkedNodes)

  let selectedKeys: string[] = []

  if (checked && checked.checkedKeys && checked.checkedKeys.length > 0) {
    // 如果 checkedKeys 有效，使用它
    selectedKeys = checked.checkedKeys.filter((key: any) => key !== undefined)
    console.log('从 checkedKeys 获取:', selectedKeys)
  }

  // 如果 checkedKeys 无效，从 checkedNodes 中提取 ID
  if (selectedKeys.length === 0 && checked && checked.checkedNodes) {
    selectedKeys = checked.checkedNodes
      .filter((node: any) => node && node.id)
      .map((node: any) => node.id)
    console.log('从 checkedNodes 获取:', selectedKeys)
  }

  console.log('原始选中的keys:', selectedKeys)

  // 应用智能逻辑：如果父级被选中，移除其所有子级
  const optimizedKeys = getOptimizedSelectedKeys(selectedKeys)
  console.log('优化后的keys:', optimizedKeys)

  // 更新本地变量
  localSearchScope.value = optimizedKeys

  // 更新表单数据
  const newForm = { ...uploadForm.value }
  newForm.searchScope = optimizedKeys
  console.log('通过check事件更新表单:', newForm)
  emit('update:uploadForm', newForm)
}

// 监听 localSearchScope 变化（备用）
watch(localSearchScope, (newValue) => {
  console.log('watch - localSearchScope 变化:', newValue)
  console.log('watch - newValue 类型:', typeof newValue)
  console.log('watch - newValue 长度:', newValue?.length)

  // 避免无限循环，只在值真正改变时处理
  if (Array.isArray(newValue) && newValue.length > 0) {
    console.log('watch - 有效的数组变化:', newValue)
  }
}, { deep: true })

// 根据ID查找节点名称
const findNodeName = (categories: any[], targetId: string): string | null => {
  for (const category of categories) {
    if (category.id === targetId) return category.type_name
    if (category.children && category.children.length > 0) {
      const found = findNodeName(category.children, targetId)
      if (found) return found
    }
  }
  return null
}

// 查找节点的父级ID
const findParentId = (nodes: any[], targetId: string, parentId: string | null = null): string | null => {
  for (const node of nodes) {
    if (node.id === targetId) {
      return parentId
    }
    if (node.children && node.children.length > 0) {
      const result = findParentId(node.children, targetId, node.id)
      if (result !== null) return result
    }
  }
  return null
}

// 检查节点是否有子级
const hasChildren = (nodes: any[], targetId: string): boolean => {
  for (const node of nodes) {
    if (node.id === targetId) {
      return node.children && node.children.length > 0
    }
    if (node.children && node.children.length > 0) {
      const result = hasChildren(node.children, targetId)
      if (result !== null) return result
    }
  }
  return false
}

// 获取节点的所有子级ID
const getChildrenIds = (nodes: any[], targetId: string): string[] => {
  for (const node of nodes) {
    if (node.id === targetId) {
      const childrenIds: string[] = []
      if (node.children && node.children.length > 0) {
        const collectIds = (children: any[]) => {
          children.forEach((child: any) => {
            childrenIds.push(child.id)
            if (child.children && child.children.length > 0) {
              collectIds(child.children)
            }
          })
        }
        collectIds(node.children)
      }
      return childrenIds
    }
    if (node.children && node.children.length > 0) {
      const result = getChildrenIds(node.children, targetId)
      if (result.length > 0) return result
    }
  }
  return []
}

// 获取智能显示的范围项目
const getDisplayScopeItems = () => {
  console.log('getDisplayScopeItems 被调用')
  console.log('uploadForm.value.searchScope:', uploadForm.value.searchScope)

  if (!uploadForm.value.searchScope || uploadForm.value.searchScope.length === 0) {
    console.log('searchScope 为空，返回空数组')
    return []
  }

  const selectedIds = uploadForm.value.searchScope.filter((id: any) => id !== undefined)
  console.log('有效的selectedIds:', selectedIds)

  if (selectedIds.length === 0) {
    return []
  }

  const displayItems: { id: string; name: string; isParent: boolean }[] = []
  const processedIds = new Set<string>()

  // 遍历所有选中的ID
  selectedIds.forEach((id: string) => {
    if (processedIds.has(id)) return

    const name = findNodeName(enterpriseCategories.value, id)
    console.log(`查找ID ${id} 的名称: ${name}`)

    if (!name) return

    // 检查是否是父级节点
    const isParent = hasChildren(enterpriseCategories.value, id)

    if (isParent) {
      // 如果是父级节点，直接显示父级（因为经过优化后，如果父级在selectedIds中，说明用户选择了父级）
      console.log(`父级 ${id} 被选中，显示父级`)
      displayItems.push({
        id: id,
        name: name,
        isParent: true
      })
      processedIds.add(id)
    } else {
      // 如果是子级节点，检查其父级是否已被完全选中
      const parentId = findParentId(enterpriseCategories.value, id)
      if (parentId) {
        const allSiblingIds = getChildrenIds(enterpriseCategories.value, parentId)
        const selectedSiblingIds = allSiblingIds.filter(siblingId => selectedIds.includes(siblingId))

        if (selectedSiblingIds.length === allSiblingIds.length) {
          // 父级完全选中，这个子级不需要单独显示
          console.log(`子级 ${id} 的父级完全选中，不显示子级`)
        } else {
          // 父级部分选中，显示这个子级
          console.log(`子级 ${id} 的父级部分选中，显示子级`)
          displayItems.push({
            id: id,
            name: name,
            isParent: false
          })
        }
      } else {
        // 没有父级，直接显示
        displayItems.push({
          id: id,
          name: name,
          isParent: false
        })
      }
      processedIds.add(id)
    }
  })

  console.log('最终displayItems:', displayItems)
  return displayItems
}

// 优化选中的键值：如果父级被选中，移除其所有子级
const getOptimizedSelectedKeys = (selectedKeys: string[]): string[] => {
  if (!selectedKeys || selectedKeys.length === 0) {
    return []
  }

  const optimizedKeys: string[] = []
  const processedIds = new Set<string>()

  // 遍历所有选中的ID
  selectedKeys.forEach(id => {
    if (processedIds.has(id)) {
      return // 已经处理过了
    }

    // 检查这个ID是否有子级
    const childIds = getChildrenIds(enterpriseCategories.value, id)

    if (childIds.length > 0) {
      // 这是一个父级节点，检查是否所有子级都被选中
      const selectedChildIds = childIds.filter(childId => selectedKeys.includes(childId))

      if (selectedChildIds.length === childIds.length) {
        // 所有子级都被选中，只保留父级
        optimizedKeys.push(id)
        processedIds.add(id)
        // 标记所有子级为已处理
        childIds.forEach(childId => processedIds.add(childId))
        console.log(`父级 ${id} 完全选中，移除子级:`, childIds)
      } else {
        // 部分子级被选中，保留父级和选中的子级
        optimizedKeys.push(id)
        processedIds.add(id)
        selectedChildIds.forEach(childId => {
          if (!processedIds.has(childId)) {
            optimizedKeys.push(childId)
            processedIds.add(childId)
          }
        })
      }
    } else {
      // 这是一个叶子节点，检查其父级是否已经被处理
      const parentId = findParentId(enterpriseCategories.value, id)
      if (!parentId || !processedIds.has(parentId)) {
        // 父级没有被处理，保留这个子级
        optimizedKeys.push(id)
        processedIds.add(id)
      }
    }
  })

  return optimizedKeys
}

// 获取子节点ID列表
const getChildIds = (parentId: string): string[] => {
  const findChildren = (categories: any[], targetId: string): string[] => {
    for (const category of categories) {
      if (category.id === targetId) {
        return category.children ? category.children.map((child: any) => child.id) : []
      }
      if (category.children && category.children.length > 0) {
        const found = findChildren(category.children, targetId)
        if (found.length > 0) return found
      }
    }
    return []
  }

  return findChildren(enterpriseCategories.value, parentId)
}

// 移除选择的范围
const removeScopeSelection = (id: string) => {
  const displayItems = getDisplayScopeItems()
  const targetItem = displayItems.find(item => item.id === id)

  if (targetItem && targetItem.isParent) {
    // 如果移除的是父节点，需要移除所有子节点
    const childIds = getChildIds(id)
    const newScope = uploadForm.value.searchScope.filter((scopeId: string) =>
      scopeId !== id && !childIds.includes(scopeId)
    )
    const newForm = { ...uploadForm.value }
    newForm.searchScope = newScope
    emit('update:uploadForm', newForm)
  } else {
    // 移除单个节点
    const newScope = uploadForm.value.searchScope.filter((scopeId: string) => scopeId !== id)
    const newForm = { ...uploadForm.value }
    newForm.searchScope = newScope
    emit('update:uploadForm', newForm)
  }
}
</script>

<style scoped>
/* 上传抽屉样式 */
:deep(.create-doc-drawer .el-drawer) {
  border-radius: 12px 0 0 12px;
  overflow: hidden;
}

:deep(.create-doc-drawer .el-drawer__header) {
  padding: 0;
  margin-bottom: 0;
  border-bottom: 1px solid #f0f0f0;
  background: #ffffff;
}

:deep(.create-doc-drawer .el-drawer__body) {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.drawer-content {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  background: #fafbff;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.drawer-header {
  padding: 20px 24px;
  background: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.drawer-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.drawer-title .title-bar {
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  border-radius: 2px;
}



.form-content {
  padding: 24px;
}

.form-item {
  margin-bottom: 28px;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 15px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 12px;
}

.form-label-note {
  font-size: 12px;
  color: #6b7280;
  font-weight: normal;
  margin-left: 4px;
}

.required-mark {
  color: #ef4444;
  margin-left: 4px;
  font-weight: bold;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

/* 文档配置区域样式 */
.document-config-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
}

.config-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}

.config-title {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.config-item {
  margin-bottom: 20px;
}

.config-item:last-child {
  margin-bottom: 0;
}

.config-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.config-input-container {
  width: 100%;
}

.keywords-input-container {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 8px;
  background: white;
  transition: all 0.3s ease;
}

.keywords-input-container:hover {
  border-color: #5b7cff;
  box-shadow: 0 0 0 3px rgba(91, 124, 255, 0.1);
}

.keywords-display {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
  min-height: 24px;
}

.keyword-item {
  margin: 0;
  background: #f0f4ff;
  color: #5b7cff;
  border: 1px solid #e2e8f0;
}

.keyword-item:hover {
  background: #e8f2ff;
  border-color: #5b7cff;
}

.keyword-input {
  width: 100%;
}

.keyword-input :deep(.el-input__wrapper) {
  border: none;
  box-shadow: none;
  padding: 0;
}

.keyword-input :deep(.el-input__inner) {
  padding: 0;
  font-size: 14px;
}

.keyword-input :deep(.el-input__inner:focus) {
  box-shadow: none;
}

.tags-input-container {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 8px;
  background: white;
  transition: all 0.3s ease;
}

.tags-input-container:hover {
  border-color: #5b7cff;
  box-shadow: 0 0 0 3px rgba(91, 124, 255, 0.1);
}

.tags-display {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 8px;
  min-height: 24px;
}

.tag-item {
  margin: 0;
  background: #f3f0ff;
  color: #a685ff;
  border: 1px solid #e2e8f0;
}

.tag-item:hover {
  background: #e9e5ff;
  border-color: #a685ff;
}

.tag-input {
  width: 100%;
}

.tag-input :deep(.el-input__wrapper) {
  border: none;
  box-shadow: none;
  padding: 0;
}

.tag-input :deep(.el-input__inner) {
  padding: 0;
  font-size: 14px;
}

.tag-input :deep(.el-input__inner:focus) {
  box-shadow: none;
}

.form-label .el-icon {
  font-size: 18px;
}

.form-label .el-icon svg {
  width: 18px;
  height: 18px;
}

/* 图标颜色 */
.form-label:nth-child(1) .el-icon {
  color: #f59e0b; /* 文件夹图标 - 橙色 */
}

.form-item:nth-child(2) .form-label .el-icon {
  color: #10b981; /* 关键词图标 - 绿色 */
}

.form-item:nth-child(3) .form-label .el-icon {
  color: #3b82f6; /* 搜索图标 - 蓝色 */
}

.form-label-with-close {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.close-icon {
  color: #9ca3af;
  cursor: pointer;
  font-size: 18px;
  transition: color 0.3s ease;
}

.close-icon:hover {
  color: #ef4444;
}

:deep(.category-select .el-select__wrapper),
:deep(.category-tree-select .el-select__wrapper),
:deep(.doc-type-select .el-select__wrapper),
:deep(.keywords-select .el-select__wrapper),
:deep(.scope-select .el-select__wrapper),
:deep(.doc-overview-textarea .el-textarea__inner) {
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

:deep(.category-select .el-select__wrapper:hover),
:deep(.category-tree-select .el-select__wrapper:hover),
:deep(.doc-type-select .el-select__wrapper:hover),
:deep(.keywords-select .el-select__wrapper:hover),
:deep(.scope-select .el-select__wrapper:hover),
:deep(.doc-overview-textarea .el-textarea__inner:hover) {
  border-color: #5b7cff;
  box-shadow: 0 0 0 3px rgba(91, 124, 255, 0.1);
}

:deep(.doc-overview-textarea .el-textarea__inner:focus) {
  border-color: #5b7cff;
  box-shadow: 0 0 0 3px rgba(91, 124, 255, 0.1);
}

/* 树形选择器样式 */
:deep(.category-tree-select .el-tree-select__popper) {
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.category-tree-select .el-tree-node__content) {
  height: 36px;
  padding: 0 12px;
  border-radius: 4px;
  margin: 2px 4px;
  transition: all 0.2s ease;
}

:deep(.category-tree-select .el-tree-node__content:hover) {
  background-color: rgba(91, 124, 255, 0.1);
}

:deep(.category-tree-select .el-tree-node.is-current > .el-tree-node__content) {
  background-color: rgba(91, 124, 255, 0.15);
  color: #5b7cff;
  font-weight: 500;
}

:deep(.category-tree-select .el-tree-node__expand-icon) {
  color: #666;
  transition: all 0.2s ease;
}

:deep(.category-tree-select .el-tree-node__expand-icon.expanded) {
  transform: rotate(90deg);
}

.upload-area {
  /* border: 1px solid #e5e7eb; */
  border-radius: 12px;
  /* overflow: hidden; */
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.upload-zone {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 20px;
  background: linear-gradient(135deg, #fafbff 0%, #f8f9ff 100%);
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.upload-zone:hover {
  border-color: #5b7cff;
  background: linear-gradient(135deg, #f0f4ff 0%, #e8f2ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(91, 124, 255, 0.15);
}

.upload-icon {
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.15);
}

.upload-text {
  text-align: center;
}

.upload-title {
  font-size: 16px;
  color: #374151;
  margin-bottom: 8px;
  font-weight: 500;
}

.upload-link {
  color: #5b7cff;
  cursor: pointer;
  font-weight: 600;
  text-decoration: underline;
  text-underline-offset: 2px;
}

.upload-link:hover {
  color: #4c6ef5;
}

.upload-desc {
  font-size: 13px;
  color: #9ca3af;
  margin-top: 4px;
}

.uploaded-files-list {
  padding: 20px 0;
  background: #fafbfc;
  /* border-top: 1px solid #e5e7eb; */
  max-height: 300px;
  overflow-y: auto;
}

.uploaded-file-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: white;
  border-radius: 12px;
  margin-bottom: 12px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.uploaded-file-item:last-child {
  margin-bottom: 0;
}

.uploaded-file-item:hover {
  border-color: #5b7cff;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.1);
  transform: translateY(-1px);
}

.uploaded-file-item.current-file {
  border-color: #a685ff;
  background: #f3f0ff;
  box-shadow: 0 4px 12px rgba(166, 133, 255, 0.15);
}

.uploaded-file-item.current-file:hover {
  border-color: #a685ff;
  background: #e9e5ff;
  box-shadow: 0 6px 16px rgba(166, 133, 255, 0.2);
}

.file-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  position: relative;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background-color: rgba(0,0,0,.1);
}

.file-icon::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 12px 12px 0;
  border-color: transparent rgba(255, 255, 255, 0.3) transparent transparent;
  z-index: 2;
}

.file-type-badge {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0;
  background: rgba(0, 0, 0, 0.2);
  color: white;
  font-size: 10px;
  font-weight: 600;
  text-align: center;
  letter-spacing: 0.5px;
}

/* 文件类型图标样式 */
.file-icon-word {
  background: linear-gradient(135deg, #2B579A 0%, #1e3a8a 100%);
}

.file-icon-pdf {
  background: linear-gradient(135deg, #FF6B6B 0%, #dc2626 100%);
}

.file-icon-excel {
  background: linear-gradient(135deg, #217346 0%, #166835 100%);
}

.file-icon-ppt {
  background: linear-gradient(135deg, #D24726 0%, #b83b1e 100%);
}

.file-icon-txt {
  background: linear-gradient(135deg, #6B7280 0%, #4B5563 100%);
}

.file-icon-default {
  background: linear-gradient(135deg, #6B7280 0%, #4B5563 100%);
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 15px;
  color: #374151;
  font-weight: 600;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-details {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.file-size {
  font-size: 13px;
  color: #9ca3af;
  font-weight: 500;
}

.keywords-badge {
  font-size: 11px;
  color: #a685ff;
  background: #f3f0ff;
  padding: 2px 6px;
  border-radius: 10px;
  display: inline-block;
  width: fit-content;
}

.tags-badge {
  font-size: 11px;
  color: #10b981;
  background: #ecfdf5;
  padding: 2px 6px;
  border-radius: 10px;
  display: inline-block;
  width: fit-content;
}

.file-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.action-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e5e7eb;
  background: white;
}

.preview-icon:hover {
  background: #f0f4ff;
  border-color: #5b7cff;
  color: #5b7cff;
  transform: scale(1.05);
}

.delete-icon:hover {
  background: #fef2f2;
  border-color: #ef4444;
  color: #ef4444;
  transform: scale(1.05);
}

/* 渐变按钮样式 */
.gradient-btn {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%);
  border: none;
  color: white;
  padding: 10px 24px;
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(91, 124, 255, 0.3);
}

.gradient-btn:hover {
  background: linear-gradient(90deg, #4c6ef5 0%, #9c7eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.4);
}

.gradient-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(91, 124, 255, 0.3);
}

.minimal-btn {
  padding: 10px 24px;
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e5e7eb;
  background: white;
}

.minimal-btn--secondary {
  background: #f8f9fa;
  color: #6b7280;
  border-color: #e5e7eb;
}

.minimal-btn--secondary:hover {
  background: #e9ecef;
  border-color: #d1d5db;
}

/* AI审核结果页面样式 */
.ai-review-content {
  padding: 24px;
}

.review-header {
  margin-bottom: 24px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-radius: 12px;
  border: 1px solid #e8f2ff;
}

.review-info {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}

.info-item {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

.review-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.title-icon {
  font-size: 20px;
  color: #5b7cff;
}

.review-count {
  margin-left: auto;
  font-size: 14px;
  color:#ff4d4f;
  font-weight: 400;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  padding: 4px 12px;
  border-radius: 12px;
}

.review-results-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.review-result-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
  background: white;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.review-result-item:hover {
  border-color: #5b7cff;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.1);
  transform: translateY(-1px);
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-status {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 8px;
}

.result-status.success {
  background: #e8f5e8;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.result-status.error {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.result-filename {
  font-size: 15px;
  color: #374151;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

/* 审核结果按钮样式 */
:deep(.review-action-btn.el-button--primary.is-plain) {
  color: #5b7cff !important;
  border-color: #5b7cff !important;
  background: transparent !important;
  font-size: 12px;
  padding: 6px 12px;
}

:deep(.review-action-btn.el-button--primary.is-plain:hover) {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: white !important;
  border-color: transparent !important;
}

/* 禁用状态的按钮样式 */
:deep(.review-action-btn.el-button--primary.is-plain.is-disabled) {
  color: #c0c4cc !important;
  border-color: #e4e7ed !important;
  background: #f5f7fa !important;
  cursor: not-allowed !important;
}

/* 审核状态样式 */
.success-status {
  color: #10b981;
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.error-status {
  color: #ef4444;
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

.scope-tree-select {
  margin-top: 8px;
}

/* 下拉框位置样式 */
:deep(.scope-tree-popper) {
  z-index: 9999 !important;
}

:deep(.scope-tree-select .el-tree-select__popper) {
  transform: translateY(0) !important;
}

.selected-scope-display {
  margin-top: 12px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.selected-scope-title {
  font-size: 12px;
  color: #606266;
  margin-bottom: 6px;
}

.selected-scope-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.selected-scope-tags .el-tag {
  margin: 0;
}

/* 审核步骤概述样式 */
.review-overview {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8f2ff;
}

.overview-label {
  font-size: 14px;
  color: #374151;
  font-weight: 600;
  margin-bottom: 8px;
}

.overview-content {
  font-size: 13px;
  color: #6b7280;
  line-height: 1.6;
  background: rgba(243, 244, 246, 0.5);
  padding: 12px;
  border-radius: 8px;
  border-left: 3px solid #5b7cff;
}
</style>
